<style scoped>
</style>
<template>
  <van-popup v-model:show="is_show" round position="bottom" safe-area-inset-bottom teleport="body">
    <van-date-picker v-model="value_arr" title="选择日期" :columns-type="columns_type" @cancel="on_cancel" @confirm="on_confirm" />
  </van-popup>
</template>

<script>
import {reactive} from 'vue';
import s94Mjs from "s94-js";
import {s94_event} from "@/js/s94_tool.js";

const _this = reactive({
  is_show: false,
  confirm: ()=>{},
  cancel: ()=>{},

  fmt: 'Y-M-D',
  value: '',

  columns_type: [],
  value_arr: [],
  option_arr: [],
})

/**选择日期
 * @param {string} fmt
 * @param {string} value
 * @returns {Promise<string>}
 */
export function select_date(fmt, value){
  _this.value = value || '';
  _this.fmt = fmt || 'Y-M-D';
  _this.columns_type = [];
  if (/y/i.test(_this.fmt)) _this.columns_type.push('year');
  if (/m/i.test(_this.fmt)) _this.columns_type.push('month');
  if (/d/i.test(_this.fmt)) _this.columns_type.push('day');

  let date = new Date();
  try {
    if (_this.value) date = s94Mjs.strtodate(_this.value, fmt);
  } catch (e) {}
  _this.value_arr = [];
  _this.option_arr = [];
  _this.columns_type.forEach((v,i)=>{
    let row={};
    switch (v) {
      case 'year':{
        row.value = row.text = s94Mjs.to_string(date.getFullYear());
      }break;
      case 'month':{
        let val = s94Mjs.to_string(date.getMonth()+1);
        row.value = row.text = val < 10 ? '0'+val : val;
      }break;
      case 'day':{
        row.value = row.text = s94Mjs.to_string(date.getDate());
      }break;
    }
    _this.value_arr.push(row.value)
    _this.option_arr.push(row);
  })

  _this.is_show = true;
  return new Promise((resolve, reject)=>{
    _this.confirm = resolve;
    _this.cancel = reject;
  })
}
select_date._this = _this;
select_date.hide = function(){
  _this.is_show = false;
}

s94_event('router.after', ()=>{
  _this.is_show = false;
})

export default {
  data(){
    return _this;
  },
  methods: {
    on_cancel(){
      this.is_show = false;
      this.cancel();
    },
    on_confirm(picker_data){
      this.option_arr = picker_data.selectedOptions;
      this.value_arr = picker_data.selectedValues;
      let date = new Date();
      this.columns_type.forEach((type,i)=>{
        let val = parseInt(this.value_arr[i]);
        switch (type) {
          case 'year': date.setFullYear(val); break;
          case 'month': date.setMonth(val-1); break;
          case 'day': date.setDate(val); break;
        }
      })
      this.value = s94Mjs.date(this.fmt, date);

      this.is_show = false;
      this.confirm(this.value);
    }
  },
  mounted() {

  }
}
</script>